//
//  VideoDetailController.swift
//  maopu
//
//  Created by 黄海波 on 2017/4/6.
//  Copyright © 2017年 maopu. All rights reserved.
// 视频播放页

import UIKit
//import BarrageRenderer
//import NVActivityIndicatorView

class VideoDetailController: BaseViewController , BarrageDelegate , UITextFieldDelegate{
    
    fileprivate var player: BMPlayer!
    fileprivate var renderer:BarrageRenderer!
    fileprivate let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    
    fileprivate var bottomView:UIView!
    fileprivate var sendBarrageBtn:UIButton! //发送弹幕按钮
    fileprivate var switchBtn:UIButton!  //弹幕显示开关按钮
    
    fileprivate var commentView:UIView!
    fileprivate var textField:UITextField!
    fileprivate var colseBtn:UIButton!
    fileprivate var hideKeyBoadrBtn:UIButton!
    
    fileprivate var playTimeUIProgressView:UIProgressView!  //底部进度条
    
    fileprivate var timer:Timer!
    var url:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        appDelegate.blockRotation = true
        self.view.backgroundColor = UIColor.black
        
        self.initBottomView()
        self.resetPlayerManager()
        self.preparePlayer()
        self.setupPlayerResource()
        
        self.initBarrageRenderer()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: false)
        
        //获取设备旋转方向的通知,即使关闭了自动旋转,一样可以监测到设备的旋转方向
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        //旋转屏幕通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.onDeviceOrientationChange(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
        // 使用手势返回的时候，调用下面方法
        if player != nil{
            player.autoPlay()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: false)
        
        NotificationCenter.default.removeObserver(self)
        
        appDelegate.blockRotation = false
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        if player != nil{
            player.pause(allowAutoPlay: true)
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        player.prepareToDealloc()
        
    }
    
    deinit {
        // 使用手势返回的时候，调用下面方法手动销毁
        player.prepareToDealloc()
        if renderer != nil {
            renderer.stop()
            renderer.view.removeFromSuperview()
            renderer = nil
        }
    }
    
    //MARK:键盘显示通知
    func keyBoardWillShow(_ note:Notification){
        self.commentView.isHidden = false
        self.view.bringSubview(toFront: self.commentView)
        self.stop()
        KeyBoardUtils.shared.keyBoardWillShow(note, showView: self.commentView) { (keyBoardHeight) in
//            self.commentView.transform = CGAffineTransform(translationX: 0,y: -(keyBoardHeight)) //让view跟随键盘弹起来
            self.hideKeyBoadrBtn.frame = CGRect.init(x: 0, y: 0, width: AppWidth, height: AppHeight - keyBoardHeight - 50)
            if self.hideKeyBoadrBtn.superview == nil{
                self.view.bringSubview(toFront: self.hideKeyBoadrBtn)
                self.view.addSubview(self.hideKeyBoadrBtn)
            }
        }
    }
    //MARK:键盘消失通知
    func keyBoardWillHide(_ note:Notification){
        KeyBoardUtils.shared.keyBoardWillHide(note, hideView: self.commentView) {
            self.commentView.isHidden = true
            self.start()
            self.hideKeyBoadrBtn.removeFromSuperview()
            self.sendBarrageBtn.isSelected = false
        }
    }
    
    fileprivate func initBottomView(){
        self.bottomView = UIView()
        self.bottomView.backgroundColor = UIColor.video_bottomViewBgColor()
        self.view.addSubview(self.bottomView)
        
        self.bottomView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(0)
            make.right.equalTo(self.view).offset(0)
            make.height.equalTo(50)
            make.bottom.equalTo(self.view).offset(0)
        }
        
        self.sendBarrageBtn = UIButton.init(type: .custom)
        self.sendBarrageBtn.backgroundColor = UIColor.lightGray
        self.sendBarrageBtn.titleLabel?.font = UIFont.BoldSysFont(13)
        self.sendBarrageBtn.setTitle("发个弹幕呗", for: UIControlState())
        self.sendBarrageBtn.setTitleColor(UIColor.white, for: UIControlState())
        self.sendBarrageBtn.layer.cornerRadius = 14
        self.sendBarrageBtn.addTarget(self, action: #selector(self.sendBarrageBtnOnClick), for: .touchUpInside)
        self.bottomView.addSubview(self.sendBarrageBtn)
        self.sendBarrageBtn.snp.makeConstraints { (make) in
            make.top.equalTo(bottomView.snp.top).offset(10)
            make.left.equalTo(bottomView.snp.left).offset(50)
            make.right.equalTo(bottomView.snp.right).offset(-10)
            make.height.equalTo(30)
        }
        
        self.switchBtn = UIButton.init(type: .custom)
        self.switchBtn.backgroundColor = UIColor.clear
        self.switchBtn.setImage(UIImage.init(named: "barrage_unshow"), for: UIControlState.selected)
        self.switchBtn.setImage(UIImage.init(named: "barrage_show"), for: .normal)
        self.switchBtn.addTarget(self, action: #selector(self.showBarrageBtnClick(_:)), for: .touchUpInside)
        self.bottomView.addSubview(self.switchBtn)
        self.switchBtn.snp.makeConstraints { (make) in
            make.top.equalTo(bottomView.snp.top).offset(15)
            make.left.equalTo(bottomView.snp.left).offset(10)
            make.width.equalTo(30)
            make.height.equalTo(20)
        }
        
        self.commentView = UIView()
        self.commentView.isHidden = true
        self.commentView.backgroundColor = UIColor.video_bottomViewBgColor()
        self.view.addSubview(self.commentView)
        self.commentView.snp.makeConstraints { (make) in
            make.left.right.height.bottom.equalTo(self.bottomView)
        }
        self.textField = UITextField()
        self.textField.backgroundColor = UIColor.darkGray
        self.textField.borderStyle = .roundedRect
        self.textField.font = UIFont.LightDefaultFont(13)
        self.textField.placeholder="填装弹幕内容..."
        self.textField.returnKeyType = .send
        self.textField.keyboardType = .default
        self.textField.delegate = self
        self.commentView.addSubview(self.textField)
        self.textField.snp.makeConstraints { (make) in
            make.left.equalTo(self.commentView).offset(20)
            make.right.equalTo(self.commentView).offset(-50)
            make.height.equalTo(30)
            make.top.equalTo(self.commentView).offset(10)
        }
        
        self.hideKeyBoadrBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: AppWidth, height: 300))
        self.hideKeyBoadrBtn.backgroundColor = UIColor.clear
        self.hideKeyBoadrBtn.addTarget(self, action: #selector(self.hideKeyBoard), for: UIControlEvents.touchUpInside)
    }
    
    //MARK: 设置播放器单例，修改属性
    fileprivate func resetPlayerManager() {
        BMPlayerConf.allowLog = false
        BMPlayerConf.shouldAutoPlay = true
        BMPlayerConf.tintColor = UIColor.white
        BMPlayerConf.topBarShowInCase = .always
        BMPlayerConf.loaderType  = NVActivityIndicatorType.ballRotateChase
    }
    //MARK:初始化视频播放器
    fileprivate func preparePlayer(){
        self.player = BMPlayer(customControllView:BMPlayerCustomControlView())
//        self.player = BMPlayer()
        if self.player.controlView != nil{
            self.player.controlView.chooseDefitionView.isHidden = true
        }
        
        self.view.addSubview(self.player)
        player.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(0)
            make.left.equalTo(self.view).offset(0)
            make.right.equalTo(self.view).offset(0)
            make.height.equalTo(self.view).offset(-50)
        }
        player.delegate = self
        
        player.backBlock = { [unowned self] (isFullScreen) in
            if isFullScreen == true {
                return
            }
            let _ = self.navigationController?.popViewController(animated: true)
        }
        
        self.playTimeUIProgressView = UIProgressView()
        self.playTimeUIProgressView.isHidden = true
        self.view.addSubview(self.playTimeUIProgressView)
        playTimeUIProgressView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.player).offset(0)
            make.height.equalTo(2)
        }
        playTimeUIProgressView.progressTintColor = UIColor.video_progressTintColor()
        playTimeUIProgressView.trackTintColor = UIColor.clear
        
        self.view.bringSubview(toFront: self.playTimeUIProgressView)
        self.view.layoutIfNeeded()
        
    }
    //MARK:设置视频播放地址及开始播放
    func setupPlayerResource(){
        let asset = BMPlayerResource.init(url: URL(string: self.url)!)
        self.player.setVideo(resource: asset)
    }
    //MARK:初始化弹幕库
    fileprivate func initBarrageRenderer(){
        self.renderer = BarrageRenderer()
        self.renderer.redisplay = true
        self.renderer.canvasMargin = UIEdgeInsetsMake(70, 10, 70, 10)
        self.renderer.view.isUserInteractionEnabled = true // 若想为弹幕增加点击功能, 请添加此句话, 并在Descriptor中注入行为
        self.renderer.masked = false
        self.view.addSubview(renderer.view)
        self.view.bringSubview(toFront: renderer.view)
        
        renderer.start()
        
        timer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.autoSenderBarrage), userInfo: nil, repeats: true)
    }
    var indext = 0
    func autoSenderBarrage() {   //接收弹幕消息
        let spriteNumber :NSInteger = renderer.spritesNumber(withName: nil)
        if spriteNumber <= 20 {
            indext += 1
            renderer.receive(walkTextSpriteDescriptorWithDirection(direction: BarrageWalkDirection.R2L.rawValue))
        }
    }
    
    func walkTextSpriteDescriptorWithDirection(direction:UInt) -> BarrageDescriptor{
        let descriptor:BarrageDescriptor = BarrageDescriptor()
        descriptor.spriteName = NSStringFromClass(BarrageWalkTextSprite.self)
        descriptor.delegate = self
        descriptor.barrageId = "\(indext)"
        descriptor.params["text"] = "过场文字弹幕 \(indext)---弹幕护体"
        descriptor.params["textColor"] = UIColor(red: CGFloat(arc4random()%255) / 255, green: CGFloat(arc4random()%255) / 255, blue: CGFloat(arc4random()%255) / 255, alpha: 1)
        descriptor.params["speed"] = NSNumber.init(value: arc4random()%100 + 50)
        descriptor.params["direction"] = NSNumber.init(value: direction)
        descriptor.params["side"] = NSNumber.init(value: BarrageWalkSide.default.rawValue)
        return descriptor
    }
    
    
    func barrageSprite(_ identifier: String!) {
        Log.shared.printLog("点击的弹幕：  \(identifier)")
    }
    //MARK:点击弹幕回调
    func spriteDidClick(withId identifier: String!, text barrageText: String!) {
        Log.shared.printLog("弹幕：\(identifier!), 内容：\(barrageText!)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    //MARK:屏幕旋转通知
    func onDeviceOrientationChange(notification:NSNotification){
        
        let orientation:UIDeviceOrientation = UIDevice.current.orientation
        switch orientation {
        case .portraitUpsideDown:
            Log.shared.printLog("屏幕倒立,第3个旋转方向---电池栏在下")
            break
        case .portrait:
            self.refreshViewConstraint(orientation: .portrait)
            break
        case .landscapeLeft , .landscapeRight:
            self.refreshViewConstraint(orientation: .landscapeLeft)
            break
        default:
            break
        }
    }
    
    //MARK:根据屏幕方向刷新View
    fileprivate func refreshViewConstraint(orientation:UIDeviceOrientation){
        if orientation == .portrait{
            player.snp.remakeConstraints({ (make) in
                make.top.equalTo(self.view).offset(0)
                make.left.equalTo(self.view).offset(0)
                make.right.equalTo(self.view).offset(0)
                make.height.equalTo(self.view).offset(-50)
            })
            self.bottomView.isHidden = false
        }else{
            player.snp.remakeConstraints({ (make) in
                make.top.equalTo(self.view).offset(0)
                make.left.equalTo(self.view).offset(0)
                make.right.equalTo(self.view).offset(0)
                make.height.equalTo(self.view).offset(0)
            })
            self.bottomView.isHidden = true
        }
        self.setNeedsStatusBarAppearanceUpdate()
    }
    //MARK:发个弹幕呗按钮点击事件
    @objc fileprivate func sendBarrageBtnOnClick(){
        if sendBarrageBtn.isSelected{
            self.hideKeyBoard()
            self.sendBarrageBtn.isSelected = false
        }else{
            self.textField.becomeFirstResponder()
            self.sendBarrageBtn.isSelected = true
        }
    }
    
    fileprivate func stop(){
        self.player.pause()
        self.renderer.pause()
    }
    
    fileprivate func start(){
        self.player.play()
        self.renderer.start()
    }
    
    /// 点击空白处隐藏键盘
    func hideKeyBoard(){
        self.textField.resignFirstResponder()
    }
    
    //MARK: texField delegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.textField.text = ""
        self.hideKeyBoard()
        return false
    }
    //MARK: 控制显示隐藏弹幕
    @objc fileprivate func showBarrageBtnClick(_ button:UIButton){
        if button.isSelected{
            button.isSelected = false
            self.renderer.view.isHidden = false
            self.renderer.start()
        }else{
            button.isSelected = true
            self.renderer.view.isHidden = true
            self.renderer.pause()
        }
    }
}

extension VideoDetailController:BMPlayerDelegate{
    func bmPlayer(player: BMPlayer, playerIsPlaying playing: Bool) {
        
    }
    
    func bmPlayer(player: BMPlayer, playerStateDidChange state: BMPlayerState) {
        if state == .playedToTheEnd{
            player.controlView.hidePlayToTheEndView()
            self.setupPlayerResource()
        }else if state == .readyToPlay{
            if self.renderer != nil{
                renderer.start()
            }
        }
//        Log.shared.printLog("playerStateDidChange | state - \(state)")
    }
    
    func bmPlayer(player: BMPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) {
        self.playTimeUIProgressView.setProgress(Float(currentTime/totalTime), animated: true)
    }
    
    func bmPlayer(player: BMPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) {
        
    }
    
    func bmPlayer(controlView: BMPlayerControlView, isShow: Bool) {
        if isShow{
            self.playTimeUIProgressView.isHidden = true
        }else{
            self.playTimeUIProgressView.isHidden = false
        }
        if controlView.isFullscreen{
//            Log.shared.printLog("现在是全屏")
        }else{
//            Log.shared.printLog("现在是非全屏")
        }
    }
    
    func bmPlayer(controlView: BMPlayerControlView, didPressButton buttonType: BMPlayerControlView.ButtonType, button: UIButton) {
        switch buttonType {
        case .play: //播放状态
            Log.shared.printLog("播放")
            if self.renderer != nil{
                self.renderer.start()
            }
            break
        case .pause: //暂停状态
            Log.shared.printLog("暂停")
            if self.renderer != nil{
                self.renderer.pause()
            }
            break
        case .fullscreen: //全屏状态
            Log.shared.printLog("全屏")
            break
        case .back: //退出播放
            Log.shared.printLog("退出")
            self.hideKeyBoard()
            break
        case .replay: //重放状态
            Log.shared.printLog("重放")
            break
        case .showbarrage:
            self.renderer.view.isHidden = false
            self.renderer.start()
            break
        case .notshowbarrage:
            self.renderer.view.isHidden = true
            self.renderer.pause()
            break
        case .sendbarrage:
//            if button.isSelected{
//                
//                self.textField.becomeFirstResponder()
//            }else{
//                self.textField.resignFirstResponder()
//            }
            self.textField.becomeFirstResponder()
            break
        default:
            break
        }
    }
    
    
}


